package com.company.project.core.service.security;


import com.company.project.core.utils.Conv;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * Created by Administrator on 2018/7/4.
 */
@Slf4j
@Service
public class JwtSignServiceImpl implements SignService{

    @Value("${jwt.secret:a#$%()(234545eightfdfxiao>?N<:{LWP!W}")
    private String secret;

    @Value("${jwt.expiration:15552000000}")
    private Long expiration;

    private static final String SESSION_FIELD_NAME = "uuid";

    @Autowired
    private HttpSession session;

    public String getSign(String objectStr){
        session.setAttribute(SESSION_FIELD_NAME,objectStr);
        return JWTUtils.sign(secret,objectStr,expiration);
    }

    public boolean validateSign(String signStr){
        if(StringUtils.isEmpty(signStr)){
            return false;
        }

        String baseStr = JWTUtils.unsign(secret, signStr, String.class);
        String uuid = Conv.NS(session.getAttribute(SESSION_FIELD_NAME));

        if(StringUtils.isNotEmpty(uuid) && StringUtils.isNotEmpty(baseStr) && baseStr.equals(uuid)){
            return true;
        }
        return false;
    }

}
